<template>
  <div>
    <a-button
      type="primary"
      @click="addService"
      v-has="{ a: $route, b: 2 }"
      class="d-a-center"
      >新增页面</a-button
    >
    <!-- 左侧一级分类服务列表m-->
    <div class="main">
      <!--右侧二级分类列表 -->
      <div style="flex: 1">
        <a-table
          :columns="childrenColums"
          :data-source="childrenList"
          bordered
          :loading="loading"
          :pagination="pagination"
          @change="handleTableChange"
        >
          <!-- :scroll="{ y: 540, x: 'auto' }" -->

          <template #operation="{ record }">
            <a-button
              type="link"
              @click="editService(record, 0)"
              v-has="{ a: $route, b: 2 }"
              >编辑</a-button
            >
            <a-button
              type="link"
              @click="delService(record.id, 0)"
              v-has="{ a: $route, b: 2 }"
            >
              删除</a-button
            >
            <a-button
              type="link"
              @click="handleJump(record.id, listPage)"
              v-has="{ a: $route, b: 2 }"
              >字段配置</a-button
            >
          </template>
        </a-table>
      </div>
    </div>
  </div>
  <div>
    <a-modal :visible="visible" :footer="null" width="60%" @cancel="cancel">
      <!-- 新增服务项 -->
      <a-form
        ref="modalRef"
        :rules="rules"
        :model="modalForm"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <a-form-item label="服务名称" name="configurationName">
          <a-input
            placeholder="请输入服务名称"
            v-model:value="modalForm.configurationName"
          ></a-input>
        </a-form-item>
        <a-form-item label="分类">
          <!-- {{modalForm.value}} -->
          <a-cascader
            :show-search="{ filter }"
            v-model:value="modalForm.value"
            multiple
            :options="options"
            :load-data="loadData"
            placeholder="请选择服务分类"
            maxTagCount="6"
            :field-names="{
              label: 'name',
              value: 'id',
            }"
            @change="handleServe"
          />
        </a-form-item>
      </a-form>

      <a-divider></a-divider>
      <!-- 确定和取消 -->
      <a-row>
        <a-col :span="4" :offset="6">
          <a-button type="primary" size="large" @click="cancel">关闭</a-button>
        </a-col>
        <a-col :span="4" :offset="2">
          <a-button type="primary" size="large" @click="save">保存</a-button>
        </a-col>
      </a-row>
    </a-modal>
  </div>
</template>
<script>
import {
  reactive,
  ref,
  watch,
  computed,
  defineComponent,
  createVNode,
  toRefs,
  onMounted,
} from "vue";
import { FormInstance } from "ant-design-vue";
import {
  CheckOutlined,
  EditOutlined,
  ArrowDownOutlined,
  ArrowUpOutlined,
  ExclamationCircleOutlined,
  EditTwoTone,
  DeleteTwoTone,
  PlusOutlined,
  MinusCircleOutlined,
  LoadingOutlined,
} from "@ant-design/icons-vue";
import {
  selectAllService,
  selectAllType,
  queryserviceTypeParent,
} from "@/api/service/index.js";
import router from "@/router/index.js";
import { useRoute } from "vue-router";
import { Modal, message, notification } from "ant-design-vue";
// import type {
// 	CascaderProps
// } from 'ant-design-vue';
import Tinymce from "@/components/common/tinymce/tinymce";
import Tinymce1 from "@/components/common/tinymce/tinymce1";
import * as api from "@/api/service/report.js";
import UploadImage from "@/components/common/UploadImage.vue";
import { useModal } from "@/hooks"
export default {
  setup() {
    const route = useRoute();
    // onMounted(() => {

    // });
    const serviceAct = ref(0);
    const data = reactive({
      listPage: 1,
      toListPage: 1,
      options: [],
      serviceList: [],
      childrenList: [],
      loading: true, //表格加载
      // headerTitle: "",
      isEdit: "", //编辑or新增
      type: 2, //类型
      visible: false,
      activeKey: "0",
      uploadLoading: false,
      imageUrl: "",
      modalForm1: {},
      modalForm: {
        detail: "",
      },
      value: "",
      fileList: [],
      fileList1: [],
      fileList2: [],
      detail: "哈哈哈",
      uploadRef: "",
      columns: [
        {
          title: "套餐名称",
          dataIndex: "sonServiceName",
          width: "30%",
        },
        {
          title: "套餐价格(元)",
          dataIndex: "price",
        },
        {
          title: "套餐时长(分钟)",
          dataIndex: "duration",
        },
        {
          title: "服务次数",
          dataIndex: "serviceNum",
        },
        {
          title: "操作",
          dataIndex: "operation",
        },
      ],
      flowPop: false,
      columnsFlow: [
        {
          title: "服务规范",
          dataIndex: "serveName",
          width: "70%",
        },
        {
          title: "操作",
          dataIndex: "operation",
        },
      ],
      // 工作流程数据
      dataFlow: [
        // {
        //  id:0
        //   name: "服务流程",
        //   operation: "",
        // },
      ],
      dataSource: [],
      obj: {},
      // 修改当前套餐的index
      flag: -1,
      serviceDetails: [],
    });
    const modalRef = ref("");
    const modalRef1 = ref("");
    const editor = ref("");
    const editor1 = ref("");

    // 分页器
    const page = reactive({
      current: 1,
      pageSize: 10,
      total: 0,
    });

    // 左侧服务分类列表
    const serviceColums = [
      {
        title: "服务名称",
        dataIndex: "name",
        className: "table",
        align: "center",
        slots: {
          customRender: "service",
        },
      },
    ];

    const childrenColums = [
      {
        title: "序号",
        dataIndex: "id",
        className: "table",
        align: "center",
        // slots: {
        //   customRender: "sort",
        // },
      },
      {
        title: "服务名称",
        dataIndex: "configurationName",
        className: "table",
        align: "center",
        // sorter: (a, b) => a.price - b.price,
      },
      {
        title: "绑定的服务",
        dataIndex: "serviceId",
        className: "table",
        align: "center",
        // sorter: (a, b) => a.price - b.price,
      },
      {
        title: "操作",
        dataIndex: "operation",
        className: "table",
        align: "center",
        fixed: "right",
        slots: {
          customRender: "operation",
        },
      },
    ];
    const filter = (inputValue, path) => {
      console.log(inputValue, path);
      return path.some(
        (option) =>
          option.label.toLowerCase().indexOf(inputValue.toLowerCase()) > -1
      );
    };
    const handleServe = (value) => {
      console.log(value);

      // data.modalForm.value = value[0];
    };
    // 分页器
    const pagination = computed(() => ({
      current: page.current,
      pageSize: page.pageSize,
      pageSizeOptions: ["10", "20", "30"],
      showTotal: (total, range) => {
        return "共" + total + "条";
      },
      total: page.total,
      showQuickJumper: true,
      showSizeChanger: true,
    }));

    // 分页器改变的时候
    const handleTableChange = (pagination, filters, sorter) => {
      // console.log(pagination, "当前分页");
      page.current = pagination.current;
      page.pageSize = pagination.pageSize;
      console.log("分页Num", page.current),
        // 请求列表接口
        initChildrenList();
    };
    // 新增服务
    const addService = () => {
      console.log(data, "data111111111111111");
      data.fileList = [];
      data.fileList1 = [];
      data.visible = true;
      data.serviceDetails = [];
      data.isEdit = 2;
      data.type = 2;
      data.activeKey = "0";
    };
    // 编辑服务和服务项目
    const editService = async (item, type) => {
      data.isEdit = 1;
      console.log(item, "item");
      data.modalForm = {
        ...item,
      };
      data.visible = true;
    };
    async function initServiceDetail(id) {
      let res = await selectServiceById(id);
      if (res.success) {
        return res.object;
      }
    }
    // 删除服务和服务项目
    const delService = (key, type) => {
      const {closeModal} = useModal.confirm({
        icon: () => createVNode(ExclamationCircleOutlined),
        content: () =>
          createVNode(
            "div",
            {
              style: "color:red;",
            },
            "确定要删除当前服务配置吗"
          ),
        okType: "danger",
        onOk: async () => {
          let res = await api.deleteConfiguration({
            id: key,
          });
          if (res.success) {
            message.success("删除成功");
            initChildrenList();
            closeModal()
          }
        },
        
        class: "test",
      });
    };
    const loadData = async (selectedOptions) => {
      console.log("点击了选择", selectedOptions);

      const targetOption = selectedOptions[selectedOptions.length - 1];
      targetOption.loading = true; // load options lazily
      // 二级
      if (selectedOptions.length == 1) {
        let obj = {
          parentId: targetOption.id,
        };
        let res1 = await selectAllType(obj);
        if (res1.success) {
          res1.object.map((el) => (el.isLeaf = false)); //id是string类型的
          targetOption.children = res1.object;
          data.options = [...data.options];
        }
      } else {
        // 三级
        let obj = {
          pageNum: 1,
          pageSize: 200,
          typeId: targetOption.id,
        };
        let res2 = await selectAllService(obj);
        if (res2.success) {
          res2.object.records.map((el) => (el.name = el.serveName));
          targetOption.children = res2.object.records;
          data.options = [...data.options];
        }
      }
    };
    
   
    const headerTitle = computed(() => {
      let title = data.isEdit == 1 ? "编辑" : "新增";
      return title;
    });
    const rules = {
      kindName: [
        {
          required: true,
          message: "请输入分类名称!",
        },
      ],
    };
    const cancel = () => {
      console.log("点击了关闭");
      //置空
      data.modalForm1 = {};
      data.modalForm = {};
      data.dataSource = [];
      data.dataFlow = [];
      data.visible = false;
    };
    const handleChange = (value) => {
      data.modalForm.typeId = value;
    };
    // 保存,根据tab的绑定的key值判断编辑服务项目还是类别
    const save = () => {
      console.log(data.modalForm, "data.modalForm");

      let ref = data.activeKey == "0" ? modalRef : modalRef1;
      console.log("data.activeKey", data.activeKey);
      console.log("ref0000000", ref);
      ref.value
        .validate()
        .then(async () => {
          let obj = {};
          if (data.modalForm.id) {
            obj.id = data.modalForm.id;
          }
          obj.configurationName = data.modalForm.configurationName;
          if (data.modalForm.value.length == 0) {
            message.error("请选择对应服务");
            return;
          }
          let arr = data.modalForm.value.map((m) => {
            return m[2];
          });
          obj.serviceId = arr.join(",");
          console.log("新增服务obj", obj);
          if (obj.serviceId != "" && obj.configurationName != "") {
            let res = await api.insertConfiguration(obj);
            if (res.success) {
              message.success("操作成功");
              data.visible = false;
              data.modalForm = {};
              initChildrenList();
            }
            // 关闭弹窗
            emit("closeModal");
          } else {
            message.error("请填写所有项！");
          }
        })
        .catch((error) => {
          console.log("error");
        });
    };
    // console.log("router1111111111111", router.options.history.state.forward);
    let detailUrl = router.options.history.state.forward;
    if (detailUrl != null) {
      let detailUrlLength = detailUrl.length;
      let detailUrlLocation = detailUrl.lastIndexOf("=");
      let endData = detailUrl.substr(
        detailUrlLocation + 1,
        detailUrlLength - detailUrlLocation
      );
      data.toListPage = endData;
      console.log("endData", endData);
    }
    // console.log("page.current,data.toListPage", page.current, data.toListPage)
    if (data.toListPage != 1) {
      page.current = data.toListPage;
      console.log(222222233333333333);
      initChildrenList();
    } else {
      console.log(1111111111111111);
      initChildrenList();
    }
    initFirstServiceList();
    // 初始化服务列表
    async function initChildrenList() {
      // console.log('11111111111')
      let obj = {
        appType: "0",
        pageNum: page.current,
        pageSize: page.pageSize,
      };
      console.log("obj", obj);

      let res = await api.selectConfigurationList(obj);
      if (res.success) {
        res.object.list.map((el) => (el.key = el.id));
        // data.serviceList = res.object.records;
        data.childrenList = res.object.list;
        page.total = res.object.total;
        data.loading = false;
        data.listPage = res.object.pageNum;
        // initChildrenList(res.object.records[0].id);
      }
    }
    async function initFirstServiceList() {
      queryserviceTypeParent().then((r) => {
        r.object.map((m) => (m.name = m.kindName));
        r.object.map((el) => (el.isLeaf = false));
        data.options = [...r.object];
        // const options: CascaderProps['options'] = data.options;
        // initServiceList(data.tabs[0].id)
      });
    }
    const closeFlowPop = () => {
      data.flowPop = false;
      formRef.value.resetFields();
      dynamicValidateForm.serveName = "";
      dynamicValidateForm.users = [];
      dynamicValidateForm.id = [];
      dynamicValidateForm.isEdit = false;
    };
    const methods = {
      handleFlowPop() {
        data.flowPop = true;
      },
      handleAdd() {
        let idEdit = data.dataSource.some((i) => i.isEdit);
        if (idEdit) return;
        const newData = {
          key: ``,
          sonServiceName: ``,
          price: "",
          duration: "",
          serviceNum: "",
          operation: "",
          isEdit: true,
        };
        data.dataSource.push(newData);
      },
      handleEdit(ind) {
        data.flag = ind;
        // data.dataSource = data.dataSource.map(i => i.isEdit=false)
        data.dataSource[ind].isEdit = true;
        data.obj = {
          ...data.dataSource[ind],
          isEdit: true,
        };
      },
      handleDelete(ind) {
        data.dataSource.splice(ind, 1);
      },
      handleDeleteDataFlow(i) {
        data.dataFlow.splice(i, 1);
      },

      handleSave() {
        console.log(data.obj, "======");
        if (
          !(
            data.obj &&
            data.obj.sonServiceName &&
            data.obj.price &&
            data.obj.duration
          )
        ) {
          message.error("请输入名称、价格、时长");
          return;
        }
        if (data.flag > -1) {
          data.dataSource[data.flag] = {
            sonServiceName: data.obj.sonServiceName,
            price: data.obj.price,
            duration: data.obj.duration,
            serviceNum: data.obj.serviceNum,
            operation: "",
            id: data.obj.id,
          };
          data.flag = -1;
        } else {
          data.dataSource.pop();
          data.dataSource.push({
            sonServiceName: data.obj.sonServiceName,
            price: data.obj.price,
            serviceNum: data.obj.serviceNum,
            duration: data.obj.duration,
            operation: "",
          });
        }

        data.obj = {};
      },
    };
    // 工作流程
    const formRef = ref();
    const dynamicValidateForm = reactive({
      serveName: "",
      users: [],
      id: Date.now(),
    });
    const handleEditFlow = (item, index) => {
      debugger;
      console.log(data.dataFlow[index], "00000000");
      dynamicValidateForm.isEdit = true;
      dynamicValidateForm.serveName = item.serveName;
      dynamicValidateForm.id = item.id;
      dynamicValidateForm.users = JSON.parse(item.users);

      data.flowPop = true;
    };
    const removeService = (index) => {
      // let index = data.serviceDetail.indexOf(item);
      // if (index !== -1) {
      data.serviceDetails.splice(index, 1);
    };
    const removeUser = (item) => {
      let index = dynamicValidateForm.users.indexOf(item);
      // if (index !== -1) {
      dynamicValidateForm.users.splice(index, 1);
      // }
    };
    const addServiceDetail = () => {
      console.log(
        data.serviceDetails,
        "res.serviceDetailsres.serviceDetails-----"
      );

      data.serviceDetails.push({
        serviceDetailTitle: "",
        serviceDetail: "",
      });
    };
    const addUser = () => {
      dynamicValidateForm.users.push({
        first: "",
        last: "",
        id: Date.now(),
      });
      console.log(dynamicValidateForm.users, "-------");
    };
    const handleJump = (id, listPage) => {
      router.push({
        path: "/content/report/options",
        query: {
          id: id,
          listPage: listPage,
        },
      });
    };
    return {
      formRef,
      dynamicValidateForm,
      removeUser,
      addUser,
      ...toRefs(data),
      ...methods,
      childrenColums,
      pagination,
      serviceAct,
      serviceColums,
      addService,
      delService,
      editService,
      handleTableChange,
      modalRef,
      labelCol: {
        style: {
          width: "150px",
          fontWeight: "bold",
        },
      },
      wrapperCol: {
        span: 12,
      },
      rules,
      modalRef1,
      handleChange,
      save,
      cancel,
      headerTitle,
      editor,
      editor1,
      closeFlowPop,
      handleEditFlow,
      addServiceDetail,
      removeService,
      handleJump,
      loadData,
      filter,
      handleServe
    };
  },
  components: {
    CheckOutlined,
    EditOutlined,
    ExclamationCircleOutlined,
    EditTwoTone,
    DeleteTwoTone,
    ArrowUpOutlined,
    ArrowDownOutlined,
    PlusOutlined,
    LoadingOutlined,
    Tinymce,
    Tinymce1,
    UploadImage,
    MinusCircleOutlined,
  },
};
</script>

<style scoped lang="less">
.flex {
  display: flex;
  align-items: center;
}

.main {
  display: flex;
  margin-top: 30px;
}

.ant-upload-text {
  padding: 40px;
  display: flex;
}

.service {
  display: flex;
  justify-content: space-between;

  // 服务激活样式
  .name-act {
    color: #2a9d8f;
    font-weight: bolder;
  }

  .edit {
    padding: 0px 5px;
  }
}

.process {
  display: flex;

  .process-list {
    margin-right: 20px;
    display: flex;
    flex-direction: column;

    .num {
      width: 50px;
      height: 50px;
      border: solid 1px #999;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 18px;
    }

    .img {
      width: 50px;
      height: 50px;
      background-color: tomato;
      margin: 10px 0px;
    }

    .title {
    }
  }
}

.table {
  width: 100%;
  border-left: 1px solid #eee;
  border-top: 1px solid #eee;

  tr {
    td {
      input {
        border: 1px solid #aaa !important;
        width: 97% !important;
      }
    }

    th,
    td {
      text-align: center;
      border-right: 1px solid #eee;
      border-bottom: 1px solid #eee;
    }
  }
}

.myhtml {
  width: 160%;
  height: 140%;
  padding: 8rpx 6rpx;
  border: 2rpx solid #d9d9d9;
  border-radius: 2px;
  color: rgba(0, 0, 0, 0.25);
  background: #f5f5f5;
}

.flowWrap {
  .f_item {
    padding: 20px 0 !important;
  }

  .left {
    font-size: 16px;
    font-weight: 500;
    margin-bottom: 22px;
    margin-right: 30px;

    .spot {
      color: red;
    }
  }
}

.ant-form-item {
  margin-bottom: 0px;
}
</style>
